import request from '../plugin/axios'
import axios from 'axios' // 引用axios
// import { Promise } from 'es6-promise' // 引入Promise

// axios 配置和拦截器都不用了，这里我使用了一个动态配置数据请求地址，在App.vue中，代码在下面，这个也不是必须的。

// ^_^下面都设置一个默认的头部，使用的时候可以传入数据覆盖^_^,例如使用fetch(GET)方法时，没有请求数据，但是请求头有变化，则应写成 fetch("地址", {}, {"这里写头部的内容"})   记住没数据用一个空对象占位置
/**
 * fetch 请求方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function fetch (url, params = {}, headers = {
  'Content-Type': 'application/json', // 设置跨域头部
  'Authorization': 'JWT ' + sessionStorage.getItem('authToken')
}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params,
      headers: headers
    })
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err.response)
      })
  })
}

/**
 * post 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post (url, data = {}, config = {
  headers: {
    'Content-Type': 'application/json', // 设置跨域头部
    'Authorization': 'JWT ' + sessionStorage.getItem('authToken'),
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
    'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS'
  }
}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data, config)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err.response)
      })
  })
}

/**
 * patch 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch (url, data = {}, config = {
  'headers': {
    'Content-Type': 'application/json', // 设置跨域头部
    'Authorization': 'JWT ' + sessionStorage.getItem('authToken')
  }
}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data, config)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err.response)
      })
  })
}

/**
 * put 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function put (url, data = {}, config = {
  'headers': {
    'Content-Type': 'application/json', // 设置跨域头部
    'Authorization': 'JWT ' + sessionStorage.getItem('authToken')
  }
}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data, config)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err.response)
      })
  })
}

export function login (url, user, passwd) {
  axios.defaults.baseURL = url
  let p = { name: user, password: passwd }
  return post('/client/login', p)
}

export function table (model, { domain = [], fields = '', order = '', offset = 0, limit = 25 }) {
  let params = {
    model: model,
    domain: typeof domain === 'string' ? domain : JSON.stringify(domain),
    order: order,
    limit: limit,
    offset: offset.toString(),
    fields: fields.toString(),
    lang: 'zh_CN'
  }
  return request({
    url: '/client/table',
    method: 'post',
    data: params
  })
}

export function read (model, args) {
  let params = {
    'jsonrpc': '2.0',
    'method': 'call',
    'params': {
      'args': args,
      'model': model,
      'method': 'read',
      'kwargs': {
        'context': {
          'lang': 'zh_CN',
          'tz': 'Asia/Shanghai'
        }
      }
    }
  }
  return request({
    url: 'web/dataset/call_kw/' + model + '/read',
    method: 'post',
    data: params
  })
}

export function modelMethod (model, method, args) {
  let params = {
    'jsonrpc': '2.0',
    'method': 'call',
    'params': {
      'args': args,
      'model': model,
      'method': method,
      'kwargs': {
        'context': {
          'lang': 'zh_CN',
          'tz': 'Asia/Shanghai'
        }
      }
    }
  }
  return request({
    url: 'web/dataset/call_kw/',
    method: 'post',
    data: params
  })
}

export function searchRead (model, { domain = [], fields = [], order = '', groupby = [], limit = 25 }) {
  let params = {
    'jsonrpc': '2.0',
    'method': 'call',
    'params': {
      'args': [],
      'model': model,
      'method': 'search_read',
      'kwargs': {
        'context': {
          'lang': 'zh_CN',
          'tz': 'Asia/Shanghai'
        },
        domain: domain,
        fields: fields,
        limit: limit,
        order: order
      }
    }
  }
  return request({
    url: 'web/dataset/call_kw/' + model + '/search_read',
    method: 'post',
    data: params
  })
}

export function readGroup (model, { domain = [], fields = [], order = '', groupby = [] }) {
  let params = {
    'jsonrpc': '2.0',
    'method': 'call',
    'params': {
      'args': [],
      'model': model,
      'method': 'read_group',
      'kwargs': {
        'context': {
          'lang': 'zh_CN',
          'tz': 'Asia/Shanghai'
        },
        domain: typeof domain === 'string' ? JSON.parse(domain) : JSON.stringify(domain),
        fields: fields,
        'groupby': groupby,
        'orderby': order,
        'lazy': true
      }
    }
  }
  return request({
    url: 'web/dataset/call_kw/' + model + '/read_group',
    method: 'post',
    data: params
  })
}
export function tree (model, { domain = [], groupby = '', fields = '', order = '', offset = 0, limit = 25 }) {
  let params = {
    model: model,
    domain: typeof domain === 'string' ? domain : JSON.stringify(domain),
    order: order,
    limit: limit,
    offset: offset,
    fields: fields.toString(),
    lang: 'zh_CN',
    group_by: groupby
  }
  return request({
    url: '/client/tree',
    method: 'post',
    data: params
  })
}

export function nameSearch (model, { name = '', offset = 0, limit = 25 }) {
  console.info('search')
  let params = {
    model: model,
    name: name,
    limit: limit,
    offset: offset,
    lang: 'zh_CN'
  }
  return request({
    url: '/client/search',
    method: 'post',
    data: params
  })
}

export function recordWrite (model, valueDict) {
  let params = { model: model, value: valueDict, lang: 'zh_CN' }
  return request({
    url: '/client/record_write',
    method: 'post',
    data: params
  })
}

export function defaultValue (model) {
  let param = { model: model, lang: 'zh_CN' }
  return request({
    url: '/client/default_value',
    method: 'post',
    data: param
  })
}

export function queryFields (model, type = null) {
  let param = { model: model, lang: 'zh_CN', type: type }
  return request({
    url: '/client/fields',
    method: 'post',
    data: param
  })
}

export function record (model, activeId) {
  let params = { model: model, active_id: activeId, lang: 'zh_CN' }
  return request({ url: '/client/record', method: 'post', data: params })
}

export function unlink (model, { activeId = '', domain = [] }) {
  let params = {
    model: model,
    active_id: activeId,
    domain: typeof domain === 'string' ? domain : JSON.stringify(domain),
    lang: 'zh_CN'
  }
  return request({
    url: '/client/record_unlink',
    method: 'post',
    data: params
  })
}

export function one2many (model, field, fields, activeId) {
  let params = { model: model, field: field, fields: fields, active_id: activeId, lang: 'zh_CN' }
  return request({
    url: '/client/one2many',
    method: 'post',
    data: params
  })
}

export let baseField = ['write_date', 'create_date', 'create_uid', '__last_update', 'write_uid', 'id', 'display_name']
export let seoField = ['website_meta_description', 'website_meta_keywords', 'website_meta_title']
export let websiteField = ['website_url'] // 'website_published'存在于mail.meaasge
export let ratingField = ['rating_count', 'rating_last_feedback', 'rating_last_image', 'rating_last_value'] // 'rating_ids' 存在于mail.meaasge
export let msgField = ['message_follower_ids', 'message_ids', 'message_is_follower', 'message_last_post', 'message_needaction', 'message_needaction_counter', 'message_unread', 'message_unread_counter', 'website_message_ids']
